<script setup lang="ts">
import { ElMessage, ElMessageBox, UploadFile } from "element-plus";
import { nextTick, ref } from "vue";
import { ApiStudent } from "../../api";

const model = ref<API.Student.AvatarUpdate>({
  stu_id: 0,
  stu_avatar_old: null,
  stu_avatar_new: "",
});
const show = ref<boolean>(false);
const formData = new FormData();
const imgUrl = ref<string>("");
const changeHandler = (uploadFile: UploadFile) => {
  imgUrl.value = window.URL.createObjectURL(uploadFile.raw as Blob);
  formData.delete("avatar");
  formData.append("avatar", uploadFile.raw as Blob);
};
const emits = defineEmits<{
  (name: "save", model: API.Student.AvatarUpdate): void;
}>();

const cancel = async () => {
  await ElMessageBox.confirm("确定取消吗？", "提示", { type: "warning" });
  nextTick(() => (show.value = false));
};
const save = async () => {
  model.value.stu_avatar_new = await ApiStudent.avatarUpload(formData);
  await ApiStudent.avatarUpdate(model.value);
  emits("save", model.value);
  ElMessage.success("存档成功");
  nextTick(() => (show.value = false));
};
defineExpose({
  begin: (data: UI.List) => {
    imgUrl.value = data.stu_avatar ? "http://localhost:3002" + data.stu_avatar : "";
    model.value.stu_avatar_old = data.stu_avatar;
    model.value.stu_id = data.stu_id
    nextTick(() => {
      show.value = true;
    });
  },
});
const cardBodyStyle = {
   height: "100px",
   width: "100px",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  borderRadius: "10px",
  backgroundColor: "#4ea8f8",
  cursor: "pointer"
  }
</script>

<template>
  <el-dialog title="图片存档" width="800px" v-model="show">
    <div class="avatar">
      <el-row :gutter="20">
        <el-col :span="10" :offset="3">
          <el-image fit="cover" :src="imgUrl" alt="个人照片" />
          <!-- <p class="error-message">还没照片，抓紧存档吧</p> -->
        </el-col>
        <el-col :span="10">
          <el-upload
            list-type="picture"
            :show-file-list="false"
            accept=".jpg,.png,.jpeg"
            :on-change="changeHandler"
            :auto-upload="false"
          >
            <el-card :body-style="cardBodyStyle">
              <el-icon><Plus/></el-icon>
            </el-card>
          </el-upload>
          <p class="upload-limit">
            只能上传 .jpg ,.jpeg或 .png 文件，且大小不超过 2MB。
          </p>
        </el-col>
      </el-row>
    </div>
    <div slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="save">存 档</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-dialog {
    .avatar { 
      .el-image{
        width: 300px;
        height: auto;
        }
        .el-icon{
            font-size: 20px;
        }
    }
}
</style>
